<template>
  <div style="background: white;">
    <div class="top-content-view">
      <div class="top-view1">
        <div class="top-view-label">自定义字段</div>
        <div class="top-view-subview">
          <span class="top-select-label" @click="newCustomerClick">
            <a-modal
              title="新建字段分类"
              :visible="visibleNewCustomer"
              :confirm-loading="newConfirmLoading"
              @ok="newCustomerHandleOk"
              @cancel="newCustomerHandleCancle"
            >
              <a-input :value="caregoryValue" placeholder="请输入字段分类名称" @change="onChange" />
            </a-modal>
            <a-icon type="file-add" />新建字段分类
          </span>

          <span class="top-select-label" style="margin-left: 20px;" @click="newFieldCustomerClick">
            <a-modal
              title="新建字段"
              :visible="visibleFieldNewCustomer"
              :confirm-loading="newFieldConfirmLoading"
              @ok="fieldCustomerHandleOk"
              @cancel="fieldHandleCancel"
            >
              <newfield-from-item
                ref="newFieldItem"
                :creategory-enum="creategoryEnum"
                :system-enum="systemEnum"
                :customer-list="customFieldCategoryListVOList"
              />
            </a-modal>
            <a-icon type="file-add" />新建字段
          </span>
        </div>
      </div>
      <div class="top-content-sublabel">
        全企业通用的自定义字段，满足更多场景需要。
      </div>
      <div class="top-content-separactor" />

      <div>
        <a-input class="top-inputSearch" placeholder="搜索字段" @change="searchChange">
          <a-icon slot="prefix" type="search" style="color: rgba(0,0,0,.25)" />
        </a-input>
      </div>
    </div>

    <a-list v-if="!noSearch" item-layout="horizontal" :data-source="searchCustomFieldCategoryListVOList">
      <a-list-item slot="renderItem" :key="item.id" slot-scope="item">
        <div class="cell-item-content">
          <div class="cell-item-topView">
            <a-icon type="solution" style="margin-right:15px;" />
            <span>{{ item.name }}</span>
          </div>

          <div class="cell-item-bottomView">
            <div>
              <span class="cell-item-label">描述:</span>

              <span class="cell-item-label">{{ item.description }}</span>
            </div>

            <div style="margin-left:20px;">
              <span class="cell-item-label">最近编辑时间:</span>

              <span class="cell-item-label">{{ dateConvert(item.gmtModified) }}</span>
            </div>
          </div>
          <div>
            <div v-if="item.fieldOptions !== null">
              <span class="cell-item-label">选项:</span>

              <span class="cell-item-label">{{ item.fieldOptions }}</span>
            </div>
          </div>
        </div>

        <template slot="actions">
          <span style="margin-left:25px;" @click="showEdit(item)"> <a-icon type="edit" />编辑 </span>
        </template>
        <template slot="actions">
          <span @click="handleDelete(category)"> <a-icon type="delete" />删除 </span>
        </template>
      </a-list-item>
    </a-list>

    <a-collapse v-if="noSearch" :bordered="false">
      <a-collapse-panel
        v-for="(category, index) in customFieldCategoryListVOList"
        :key="index"
        :header="category.name + ' · ' + category.fieldCount"
      >
        <div>
          <a-button icon="edit" @click="showEditCategory(category)"> 编辑</a-button>
          <a-button icon="delete" @click="showCategoryDelete(category.id)"> 删除</a-button>
        </div>

        <a-list :key="category.id" item-layout="vertical" :data-source="category.customFieldList">
          <a-list-item slot="renderItem" :key="item.id" slot-scope="item">
            <div class="cell-item-content">
              <div class="cell-item-topView">
                <a-icon type="solution" style="margin-right:15px;" />
                <span>{{ item.name }}</span>
              </div>

              <div class="cell-item-bottomView">
                <div>
                  <span class="cell-item-label">描述:</span>

                  <span class="cell-item-label">{{ item.description }}</span>
                </div>

                <div style="margin-left:20px;">
                  <span class="cell-item-label">最近编辑时间:</span>

                  <span class="cell-item-label">{{ dateConvert(item.gmtModified) }}</span>
                </div>
              </div>
              <div>
                <div v-if="item.fieldOptions !== null">
                  <span class="cell-item-label">选项:</span>

                  <span class="cell-item-label">{{ item.fieldOptions }}</span>
                </div>
              </div>
            </div>

            <template slot="actions">
              <span style="margin-left:25px;" @click="showEdit(item)"> <a-icon type="edit" />编辑 </span>
            </template>
            <template slot="actions">
              <span @click="handleDelete(category)"> <a-icon type="delete" />删除 </span>
            </template>
          </a-list-item>
        </a-list>
      </a-collapse-panel>
    </a-collapse>
    <a-modal title="编辑字段" :visible="visibleEdit" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
      <edit-from-item
        ref="editFromListItem"
        :item-model="currentItem"
        :creategory-enum="creategoryEnum"
        :system-enum="systemEnum"
        :customer-list="customFieldCategoryListVOList"
        :default-type="currentItem.systemFieldCode"
      />
    </a-modal>

    <a-modal title="删除分类" :visible="isDeleteCategory" @ok="handleDeleteOk" @cancel="handleDeleteCancel">
      <p>您确定要删除该分类和其分类下的字段</p>
    </a-modal>

    <a-modal
      title="编辑分类"
      :visible="editCategory"
      :confirm-loading="confirmEditCategoryLoading"
      @ok="handleEditCategoryOk"
      @cancel="handleEditCategoryCancel"
    >
      <a-input :value="editCategoryValue" placeholder="请输入字段分类名称" @change="editCategoryChange" />
    </a-modal>
  </div>
</template>
<script>
import {
  customFieldCategoryDelete,
  customFieldCategoryFindById,
  customFieldCategoryListAll,
  customFieldCategorySave,
  customFieldCategoryUpdate,
  customFieldCategoryPage
} from "@/api/customFieldManager/customFieldCategory.js";

import { systemFieldListAll } from "@/api/customFieldManager/systemField.js";

import editFromItem from "./customerFromItems/editFromeItem.vue";
import newfieldFromItem from "./customerFromItems/newfieldFromItem.vue";

import {
  customFieldDelete,
  customFieldFindById,
  customFieldSave,
  customFieldUpdate,
  customFieldListAll
} from "@/api/customFieldManager/customField.js";
import { mapGetters } from "vuex";

export default {
  components: {
    editFromItem,
    newfieldFromItem
  },

  data() {
    return {
      isDeleteCategory: false,
      currentDeleteId: "",
      currentEditCategoryItem: "",
      noSearch: true,
      activeKey: ["1"],
      expandIconPosition: "left",
      editCategory: false,
      confirmEditCategoryLoading: false,
      currentItem: {},
      multiple: false,
      caregoryValue: "",
      editCategoryValue: "",
      searchValue: "",
      creategoryEnum: [
        { subjectType: "dropDown", name: "单选" },
        { subjectType: "multipleChoice", name: "多选" },
        { subjectType: "data", name: "日期" },
        { subjectType: "number", name: "数字" },
        { subjectType: "text", name: "文本" },
        { subjectType: "file", name: "文件" },
        { subjectType: "system", name: "系统" }
      ],
      systemEnum: [],
      visibleFieldNewCustomer: false,
      newFieldConfirmLoading: false,
      visibleNewCustomer: false,
      newConfirmLoading: false,
      visibleEdit: false,
      confirmLoading: false,
      visibleDelete: false,
      customFieldCategoryListVOList: null,
      searchCustomFieldCategoryListVOList: null,
      fieldList: null,
      listLoading: true,
      editLoading: false,
      customFieldCategoryQuery: {},
      searchName: undefined,
      customFieldQuery: {
        name: undefined
      },
      customFieldCategoryAddDTO: {
        name: undefined,
        description: undefined
      },
      customFieldCategoryUpdateDTO: {
        id: undefined,
        name: undefined,
        description: undefined
      },
      addDialogFormVisible: false,
      editDialogFormVisible: false,
      addRules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }]
      },
      editRules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }]
      }
    };
  },

  created() {
    this.getList();
    this.getSystemFieldListAll();
  },
  methods: {
    getList() {
      customFieldCategoryListAll(this.customFieldCategoryQuery).then(response => {
        this.customFieldCategoryListVOList = response.data;
      });
    },
    getFieldList() {
      if (!this.searchName) {
        this.fieldList = null;
        return;
      }
      this.listLoading = true;
      this.customFieldQuery.name = this.searchName;
      customFieldListAll(this.customFieldQuery).then(response => {
        this.fieldList = response.data;
        this.listLoading = false;
      });
    },
    handleFilter() {
      this.customFieldCategoryQuery.page = 1;
      this.getList();
    },
    sortChange(data) {
      if (!this.customFieldCategoryQuery.orders) {
        this.customFieldCategoryQuery.orders = [];
      }
      const { prop, order } = data;
      if (order == null) {
        // 移除排序
        this.customFieldCategoryQuery.orders = this.customFieldCategoryQuery.orders.filter(item => {
          return prop !== item.property;
        });
      } else {
        // 添加排序
        this.customFieldCategoryQuery.orders.push({
          property: "" + prop + "",
          desc: order === "descending"
        });
      }
      this.handleFilter();
    },
    resetAddDTO() {
      this.customFieldCategoryAddDTO = {
        name: undefined,
        description: undefined
      };
    },
    handleCreate() {
      this.resetAddDTO();
      this.addDialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["addDataForm"].clearValidate();
      });
    },
    createData() {
      this.$refs["addDataForm"].validate(valid => {
        if (valid) {
          customFieldCategorySave(this.customFieldCategoryAddDTO).then(() => {
            this.addDialogFormVisible = false;
            this.handleFilter();
            this.$notify({
              title: "Success",
              message: "添加成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    handleUpdate(row) {
      this.editDialogFormVisible = true;
      this.editLoading = true;
      // 从后端查询再编辑
      customFieldCategoryFindById(row.id).then(respone => {
        this.customFieldCategoryUpdateDTO = respone.data;
        this.editLoading = false;
      });
      this.$nextTick(() => {
        this.$refs["editDataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["editDataForm"].validate(valid => {
        if (valid) {
          customFieldCategoryUpdate(this.customFieldCategoryUpdateDTO).then(() => {
            this.editDialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "Success",
              message: "修改成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    handleView(row) {
      this.$notify({
        title: "Success",
        message: "Delete Successfully",
        type: "success",
        duration: 2000
      });
    },
    handleDelete(row) {
      this.$confirm("确定删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        customFieldCategoryDelete(row.id).then(() => {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        });
      });
    },
    getSortClass: function(key) {
      if (!this.customFieldCategoryQuery.orders) {
        return "";
      }
      const currOrder = this.customFieldCategoryQuery.orders.filter(item => {
        return key === item.property;
      });
      if (currOrder && currOrder.length > 0) {
        return currOrder[0].desc ? "descending" : "ascending";
      } else {
        return "";
      }
    },
    showEditCategory(item) {
      this.currentEditCategoryItem = item;
      this.editCategoryValue = this.currentEditCategoryItem.name;
      this.editCategory = true;
    },
    handleEditCategoryCancel() {
      this.editCategory = false;
    },
    handleEditCategoryOk() {
      this.editCategory = false;
      var param = {
        id: this.currentEditCategoryItem.id,
        name: this.editCategoryValue
      };

      customFieldCategoryUpdate(param).then(res => {
        this.$notify({
          title: "Success",
          message: "修改成功",
          type: "success",
          duration: 2000
        });

        this.getList();
      });
    },
    showCategoryDelete(id) {
      this.currentDeleteId = id;
      this.isDeleteCategory = true;
    },
    showEdit(item) {
      this.currentItem = item;
      this.visibleEdit = true;
    },
    handleOk() {
      this.confirmLoading = true;

      this.$refs.editFromListItem.confirmSubmit();
      var value = this.$refs.editFromListItem.resultValues;

      var param = {
        categoryId: value.category,
        description: value.des,
        name: value.note,
        systemFieldCode: value.type,
        type: value.type,
        id: this.currentItem.id
      };

      if (value.names.length !== 0) {
        var arrData = [];
        for (let index = 0; index < value.names.length; index++) {
          const element = value.names[index];
          var p = {
            sort: index,
            name: element,
            value: element
          };
          arrData.push(p);
        }
        param["choices"] = arrData;
      }

      customFieldUpdate(param)
        .then(res => {
          this.visibleEdit = false;
          this.confirmLoading = false;
          this.$notify({
            title: "Success",
            message: "修改成功",
            type: "success",
            duration: 2000
          });

          this.getList();
        })
        .catch(err => {
          console.log("debug log --> ", err);
          this.visibleEdit = false;
          this.confirmLoading = false;
        });
    },
    handleCancel(e) {
      this.visibleEdit = false;
    },
    handleDeleteOk() {
      this.isDeleteCategory = false;
      customFieldCategoryDelete(this.currentDeleteId).then(() => {
        this.$notify({
          title: "Success",
          message: "删除成功",
          type: "success",
          duration: 2000
        });
        this.getList();
      });
    },
    handleDeleteCancel() {
      this.isDeleteCategory = false;
    },
    newCustomerClick() {
      this.visibleNewCustomer = true;
    },
    newCustomerHandleOk(e) {
      this.newConfirmLoading = true;
      this.customFieldCategoryAddDTO.name = this.caregoryValue;
      customFieldCategorySave(this.customFieldCategoryAddDTO)
        .then(res => {
          this.visibleNewCustomer = false;
          this.newConfirmLoading = false;

          this.handleFilter();
          this.$notify({
            title: "Success",
            message: "添加成功",
            type: "success",
            duration: 2000
          });
        })
        .catch(err => {
          console.log("debug log --> ", err);
          this.visibleNewCustomer = false;
          this.newConfirmLoading = false;
        });
    },
    newCustomerHandleCancle(e) {
      this.visibleNewCustomer = false;
    },
    getSystemFieldListAll: function() {
      systemFieldListAll().then(res => {
        this.systemEnum = res.data;
      });
    },
    newFieldCustomerClick() {
      this.visibleFieldNewCustomer = true;
    },
    fieldHandleCancel(e) {
      this.visibleFieldNewCustomer = false;
    },

    fieldCustomerHandleOk(e) {
      this.newFieldConfirmLoading = true;
      this.$refs.newFieldItem.handleSubmit();
      var value = this.$refs.newFieldItem.resultValues;

      var param = {
        categoryId: value.category,
        description: value.des,
        name: value.titleName,
        systemFieldCode: value.type,
        type: value.type
      };

      if (value.names.length !== 0) {
        var arrData = [];
        for (let index = 0; index < value.names.length; index++) {
          const element = value.names[index];
          if (element !== undefined) {
            var p = {
              sort: index,
              name: element,
              value: element
            };
            arrData.push(p);
          }
        }
        param["choices"] = arrData;
      }

      customFieldSave(param)
        .then(res => {
          this.visibleFieldNewCustomer = false;
          this.newFieldConfirmLoading = false;
          this.$notify({
            title: "Success",
            message: "添加成功",
            type: "success",
            duration: 2000
          });

          this.getList();
        })
        // eslint-disable-next-line handle-callback-err
        .catch(err => {
          console.log("debug log --> ", err);
          this.visibleFieldNewCustomer = false;
          this.newFieldConfirmLoading = false;
        });
    },
    onChange: function(e) {
      const { value } = e.target;
      this.caregoryValue = value;
    },
    searchChange: function(e) {
      const { value } = e.target;
      this.searchValue = value;
      this.noSearch = !(this.searchValue.length !== 0);
      var param = {
        customFieldQuery: this.searchValue
      };
      customFieldCategoryListAll(param);
    },
    editCategoryChange(e) {
      const { value } = e.target;
      this.editCategoryValue = value;
    },
    newCategoryRequert() {
      customFieldCategorySave(this.customFieldCategoryAddDTO).then(() => {
        this.addDialogFormVisible = false;
        this.handleFilter();
        this.$notify({
          title: "Success",
          message: "添加成功",
          type: "success",
          duration: 2000
        });
      });
    },
    dateConvert(timestamp) {
      var date = new Date(timestamp * 1000); // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + "-";
      var M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
      var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      var h = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var m = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
      var s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    }
  }
};
</script>

<style scoped>
.top-content-view {
  display: flex;
  flex-direction: column;
  padding: 26px 24px;
  box-sizing: border-box;
}

.top-view1 {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.top-view-subview {
  display: flex;
  flex-direction: row;
}
.top-select-label {
  font-size: 14px;
  color: #1b9aee;
}

.top-view-label {
  flex: 1 1 auto;
  font-weight: 500;
  font-size: 18px;
  line-height: 24px;
  display: block;
}

.cell-item-content {
  display: flex;
  flex-direction: column;
  margin-left: 25px;
}
.cell-item-topView {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  color: #262626;
  font-family: Helvetica Neue, PingFang SC, Microsoft Yahei, "\5FAE\8F6F\96C5\9ED1", STXihei, "\534E\6587\7EC6\9ED1", sans-serif;
  font-size: 14px;
  line-height: 20px;
}
.cell-item-bottomView {
  display: flex;
  flex-direction: row;
}
.cell-item-label {
  font-size: 12px;
  color: #8c8c8c;
}
.top-content-separactor {
  margin-top: 25px;
  border-bottom: 1px solid #e5e5e5;
  margin-bottom: 20px;
}
.top-inputSearch {
  width: 250px;
  height: 40px;
}</style
>>
